<template>
    <div id="container" tabindex="0"></div>
    <div class="input-card" style="width:18rem">
        <h4>自定义事件的绑定与解绑</h4>
        <div>
            <div class="input-item">
                <button id="bt1" class="btn" style="margin-right:1rem;">绑定事件</button>
                <button id="bt2" class="btn">解绑事件</button>
            </div>
        </div>
    </div>
    <div class="info" id="tip">
        给地图绑定自定义的count事件，实现新增marker点的计数<br>
        <span id="count">总共添加了0个Marker.</span>
    </div>
</template>

<script setup>
import { onMounted } from 'vue';

onMounted(() => {

    var map = new AMap.Map('container', {
        zoom: 10,
        center: [116.39, 39.9]
    });
    var count = 0;
    var _onClick = function (e) {
        new AMap.Marker({
            position: e.lnglat,
            map: map
        })
        map.emit('count', { count: count += 1 });//触发自定义事件
    }
    var countDiv = document.getElementById('count');
    var _onCount = function (e) {
        countDiv.innerHTML = "总共添加了" + e.count + "个Marker.";
    }
    map.on("count", _onCount); //绑定自定义事件

    var bind = function () {
        remove();//防止重复绑定
        map.on("click", _onClick);//绑定地图事件
    }
    var remove = function () {
        map.off('click', _onClick);//移除地图事件
    }
    //绑定Dom事件
    var button1 = document.getElementById('bt1');
    var listener1 = button1.addEventListener('click', bind);//给div绑定单击事件  
    var button2 = document.getElementById('bt2');
    var listener2 = button2.addEventListener('click', remove);

})
</script>

<style lang="scss" scoped>
@import url('https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css');
#container {
    width: 100%;
    height: 100%;
}
</style>